package web.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import web.demo.factory.BeanFactory;
import web.demo.service.impl.FoodDetailService;
import web.demo.service.impl.FoodService;
import web.demo.service.impl.FoodTableService;
import web.demo.service.impl.FoodTypeService;
import web.demo.service.impl.OrderDetailService;
import web.demo.service.impl.OrdersService;
import web.demo.utils.WebUtils;

/**
 * Servlet基础类，所有的Servlet都继承这个方法
 * 1、统一实例化service
 * 2、统一调用doGet和doPost方法
 * 3、处理跳转
 * 4、处理前台method参数
 * */

public class BaseServlet extends HttpServlet {
	
	protected FoodTableService foodTableService=BeanFactory.getInstance("foodTableService", FoodTableService.class);
	protected FoodService foodService=BeanFactory.getInstance("foodService",FoodService.class);
	protected FoodTypeService foodTypeService=BeanFactory.getInstance("foodTypeService",FoodTypeService.class);
	protected FoodDetailService foodDetailService=BeanFactory.getInstance("foodDetailService",FoodDetailService.class);
	protected OrderDetailService orderDetailService=BeanFactory.getInstance("orderDetailService",OrderDetailService.class);
	protected OrdersService ordersService=BeanFactory.getInstance("ordersService",OrdersService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		//方法返回值（保存跳转的资源）
		Object returnValue=null;
		//获取方法名称 【约定 > 俗成： 操作类型的值，必须对应servlet中的方法名称】
		String methodName=request.getParameter("method");
		try{
			//1、获取当前的字节码文件
			Class clazz=this.getClass();
			//2、获取当前执行方法的Method类型
			Method method=clazz.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//3、执行方法
			returnValue=method.invoke(this, request,response);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		
		//跳转
		WebUtils.goTo(request,response,returnValue);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
